<template>
  <el-form
    ref="passwordFormRef"
    :model="passwordForm"
    :rules="passwordRules"
    label-width="100px"
    @submit.prevent="handleChangePassword"
  >
    <el-form-item label="原密码" prop="validPassword">
      <el-input
        v-model="passwordForm.validPassword"
        type="password"
        show-password
        placeholder="输入原密码，管理员则输入自己密码"
      />
    </el-form-item>
    <el-form-item label="新密码" prop="password">
      <el-input
        v-model="passwordForm.password"
        type="password"
        show-password
        placeholder="请输入新密码"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :loading="loading" native-type="submit">修改密码</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { changePassword } from '@/api/user'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref } from 'vue'

const loading = ref(false)
const passwordForm = reactive({
  validPassword: '',
  password: '',
})
const passwordRules = reactive<FormRules>({
  validPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === passwordForm.validPassword) {
          callback(new Error('新密码不能与原密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

const passwordFormRef = ref<FormInstance>()

const emit = defineEmits<{
  (e: 'cancel'): void
  (e: 'success'): void
}>()

const resetForm = () => {
  passwordFormRef.value?.resetFields()
  emit('cancel')
}
const props = defineProps({
  userid: {
    type: [String],
    required: true,
  },
})
const handleChangePassword = async () => {
  try {
    loading.value = true
    await passwordFormRef.value?.validate()
    await changePassword(props.userid!, passwordForm.password, passwordForm.validPassword)
    ElMessage.success('密码修改成功')
    passwordFormRef.value?.resetFields()
    emit('success')
  } finally {
    loading.value = false
  }
}
</script>
